package com.ctg.itrdc.imageconsole.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShellUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(ShellUtils.class);
	
	
	public static String ExeShell(String cmd, String logPath, String logFileName ,boolean append) {
		logger.info("The Cmd is : {} ,write to log -> {}",cmd,logPath + logFileName);
		Runtime run = Runtime.getRuntime();
		String result = "";
		BufferedReader br = null;
		BufferedReader errBr = null;
		BufferedInputStream in = null;
		BufferedInputStream errIn = null;
		OutputStreamWriter outputStreamWriter = null;
		OutputStream outputStream = null;
		try {
			if (logPath != null) {
				Process pi = run.exec("mkdir -p " + logPath);
				pi.waitFor();
			}

			Process p = run.exec(cmd);
			if (p != null) {
				logger.info( "构建执行进程号：" + p.toString() + "\r\n");

				in = new BufferedInputStream(p.getInputStream());
				br = new BufferedReader(new InputStreamReader(in));
				errIn = new BufferedInputStream(p.getErrorStream());
				errBr = new BufferedReader(new InputStreamReader(errIn));

				if (logFileName != null) {
					outputStream = new FileOutputStream(logPath + logFileName,append);
					outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
				}

				String lineStr;
				while ((lineStr = br.readLine()) != null) {
					logger.debug(lineStr);
					// 抽取关键日志信息用于后续操作
					if (lineStr != null && lineStr.contains("<FILENAME>")) {
						result += lineStr + "\r\n";
					}
					if (lineStr != null && lineStr.contains("<IMAGENAME>")) {
						result += lineStr + "\r\n";
					}					
					if (lineStr != null && lineStr.endsWith("END")) {
						result += lineStr;
					}
					if (logFileName != null) {
						// 将Shell的执行情况输出到日志文件中
						try {
							outputStreamWriter.write(lineStr + "\r\n");
							outputStreamWriter.flush();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				while ((lineStr = errBr.readLine()) != null) {
					logger.debug(lineStr);
					// 抽取关键日志信息用于后续操作
					if (logFileName != null) {
						// 将Shell的执行情况输出到日志文件中
						try {
							outputStreamWriter.write(lineStr + "\r\n");
							outputStreamWriter.flush();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}				
				p.waitFor();
			} else {
				throw new Exception( "没有pid\r\n");
			}

		} catch (Exception e) {
			logger.error("shell 执行异常:" + cmd,e);
			result = "构建失败：" + e.getMessage();
			return result;
		} finally {
			if (br != null) {
				try {
					br.close();
					in.close();
				} catch (IOException e) {
					logger.error("BufferedReader 关闭异常:" + cmd,e);
				}
			}
			if (outputStreamWriter != null) {
				try {
					outputStreamWriter.close();
				} catch (IOException e) {
					logger.error("outputStreamWriter 关闭异常:" + cmd,e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					logger.error("outputStream关闭异常:" + cmd,e);
				}
			}
			logger.info("cmd {} return :{}" ,cmd, result);
		}
		return result;
	}

	public static void main(String[] args) {
	}
	
}
